package com.ryskoo.catering.consumestatistics.repository;

import com.ryskoo.catering.constant.HCLCacheConstant;
import com.ryskoo.catering.consumestatistics.domain.ConsumeStatisticsPO;
import com.ryskoo.framework.core.repository.BasicRedisImpl;
import com.ryskoo.framework.core.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;

/**
 * @author BeHappy
 */
@Primary
@Repository
public class ConsumeStatisticsRedisImpl extends BasicRedisImpl<ConsumeStatisticsPO> implements IConsumeStatisticsRepository {
    /**
     * 缓存KEY
     */
    private static final String cacheKey = HCLCacheConstant.HCL_CONSUMESTATISTICS_KEY;

    @Autowired
    private RedisUtil redisClient;
    @Autowired
    private IConsumeStatisticsRepository consumeStatisticsRepository;

    @PostConstruct
    public void init() {
        this.setRedisClient(redisClient);
        this.setDao(consumeStatisticsRepository);
    }

    public ConsumeStatisticsRedisImpl() {
        super(cacheKey);
    }

    @Override
    public void update(ConsumeStatisticsPO consumeStatisticsPO) {
        String key = cacheKey + consumeStatisticsPO.getVendorUuid() + "_" + consumeStatisticsPO.getCustomerUuid();
        redisClient.setObject(key, consumeStatisticsPO);
        super.update(consumeStatisticsPO);
    }

    @Override
    public ConsumeStatisticsPO getByVendorAndCustomer(String vendorUuid, String customerUuid) {
        String key = cacheKey + vendorUuid + "_" + customerUuid;
        //从缓存获取对象
        ConsumeStatisticsPO po = (ConsumeStatisticsPO) redisClient.getObject(key, ConsumeStatisticsPO.class);
        if (po != null) {
            return po;
        } else {
            po = consumeStatisticsRepository.getByVendorAndCustomer(vendorUuid, customerUuid);
            if(po != null){
                redisClient.setObject(key, po);
            }
        }
        return po;
    }
}
